package ntu.metaweb.http;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.HashMap;

import ntu.metaweb.Metaweb;
import ntu.metaweb.storage.Comment;
import ntu.metaweb.storage.WebPageKey;
import ntu.metaweb.update.NewComment;
import ntu.p2p.dht.messaging.DHTUpdateObjectMessage;
import rice.Continuation;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;

@SuppressWarnings("restriction")
public class NewCommentHandler implements CommandHandler {

	@Override
	public void handleCommand(final HttpExchange exchange,
			final HashMap<String, String> params) throws IOException {
		int parent_id = params.get("parent_id").equals("-1") ? -1 :
			Integer.parseInt(params.get("parent_id").substring(8));
		Comment newComment = new Comment(params.get("username"), 
				params.get("content"), parent_id);
		final WebPageKey key = 
				new WebPageKey(URLDecoder.decode(params.get("url"), "UTF-8"));
		NewComment objectDiff = new NewComment(newComment);
		Metaweb.getInstance().getDhtApplication().update(key, 
				new DHTUpdateObjectMessage(key, objectDiff), 
				new Continuation() {

					@Override
					public void receiveException(Exception exception) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void receiveResult(Object result) {
						onReceiveResult(exchange, result);
					}
			
		});
	}

	@SuppressWarnings("restriction")
	protected void onReceiveResult(HttpExchange exchange, Object result) {
		try {
			System.out.println("sending update success...");
			Headers responseHeaders = exchange.getResponseHeaders();
			responseHeaders.set("Content-Type", "text/xml");

			exchange.sendResponseHeaders(200, 0);

			OutputStream responseBody = exchange.getResponseBody();
			String temp = "<xmlresponse>\n" 
					+ "<returncode>1</returncode>\n"
					+ "</xmlresponse>";
			responseBody.write(temp.getBytes());
			responseBody.close();
			exchange.close();
			System.out.println("close new comment handler");
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			exchange.close();
			System.out.println("close new comment handler");
		}
	}

}
